package com.qianxun.watchdog.communication;

import com.qianxun.watchdog.Master;
import com.qianxun.watchdog.util.FileUtil;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class MessageProcessor {

    private List<Socket> socketList = new ArrayList<>(16);

    private MessageHandler messageHandler;

    private Thread taskThread;

    private Object waitObject = new Object();

    public MessageProcessor(MessageHandler messageHandler){
        this.messageHandler = messageHandler;

        runTask();
    }

    public void addMessageSocket(Socket socket){
        this.socketList.add(socket);
        synchronized (waitObject){
            this.waitObject.notifyAll();
        }
    }

    public void shutdown(){
        this.taskThread.interrupt();
    }


    private void runTask(){
        this.taskThread = new Thread(()->{
            while(true){
                if(this.socketList.isEmpty()){
                    synchronized (this.waitObject){
                        try {
                            this.waitObject.wait(60 * 1000);
                        } catch (InterruptedException e) {
                            System.out.println("thread interrupted ,message processor exit");
                            break;
                        }
                    }
                }

                if(!this.socketList.isEmpty()) {
                    Socket socket = this.socketList.get(0);
                    this.socketList.remove(0);
                    String message = this.process(socket).trim();
                    if (message != null && message.trim().length() > 0 && message.indexOf(".jar") != -1) {
                        String name = message.substring(0, message.indexOf(".jar") + ".jar".length());
                        String path = name.length() == message.length() ? null : message.substring(name.length());
                        if (path != null && path.length() >= name.length() && path.endsWith(name)) {
                            try {
                                this.messageHandler.handle(new Master(name, path));
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
        });
        this.taskThread.start();
    }

    private String process(Socket socket){
        String res = null;
        try {
            byte[] bytes = FileUtil.read(socket.getInputStream());
            res = new String(bytes);
        } catch (IOException e) {
        }
        return res;
    }
}
